package com.bub.pay.framework.redis.redisson;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RList;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RMapCache;

import com.bub.pay.framework.redis.redisson.config.RedissonLockerClient;

/** 
 * @ClassName: RedissLockUtil 
 * @Description:  分布式事物锁工具类
 * @author Leo.King
 * @version V1.0   
 */
public class RedissLockUtil {

	private static RedissonLockerClient redissLock;

	public static void setLocker(RedissonLockerClient locker) {
		redissLock = locker;
	}

	/**
	 * 加锁
	 * @param lockKey
	 * @return
	 */
	public static RLock lock(String lockKey) {
		return redissLock.lock(lockKey);
	}

	/**
	 * 释放锁
	 * @param lockKey
	 */
	public static void unlock(String lockKey) {
		redissLock.unlock(lockKey);
	}

	/**
	 * 释放锁
	 * @param lock
	 */
	public static void unlock(RLock lock) {
		redissLock.unlock(lock);
	}

	/**
	 * 带超时的锁
	 * @param lockKey
	 * @param timeout 超时时间   单位：秒
	 */
	public static RLock lock(String lockKey, int timeout) {
		return redissLock.lock(lockKey, timeout);
	}

	/**
	 * 带超时的锁
	 * @param lockKey
	 * @param unit 时间单位
	 * @param timeout 超时时间
	 */
	public static RLock lock(String lockKey, TimeUnit unit, int timeout) {
		return redissLock.lock(lockKey, unit, timeout);
	}

	/**
	 * 尝试获取锁
	 * @param lockKey
	 * @param waitTime 最多等待时间
	 * @param leaseTime 上锁后自动释放锁时间
	 * @return
	 */
	public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
		return redissLock.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime);
	}

	/**
	 * 尝试获取锁
	 * @param lockKey
	 * @param unit 时间单位
	 * @param waitTime 最多等待时间
	 * @param leaseTime 上锁后自动释放锁时间
	 * @return
	 */
	public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
		return redissLock.tryLock(lockKey, unit, waitTime, leaseTime);
	}

	public static RMap<String, Object> getRmap(final String mapName) {
		return redissLock.getRmap(mapName);
	}

	public static RMapCache<String, Object> getRMapCache(final String mapName) {
		return redissLock.getRMapCache(mapName);
	}

	public static <T> RList<T> getRList(final String listName, Class<T> clz) {
		return redissLock.getRList(listName, clz);
	}

}
